package com.example.miaosh.controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.miaosh.entity.ItemModel;
import com.example.miaosh.entity.ItemStock;
import com.example.miaosh.entity.OrderCore;
import com.example.miaosh.entity.PromoModel;
import com.example.miaosh.entity.SequenceInfo;
import com.example.miaosh.entity.UserInfo;
import com.example.miaosh.service.ItemModelService;
import com.example.miaosh.service.ItemStockService;
import com.example.miaosh.service.OrderCoreService;
import com.example.miaosh.service.PromoModelService;
import com.example.miaosh.service.SequenceInfoService;
import com.example.miaosh.service.UserInfoService;
import com.example.miaosh.util.ResultUnify;
import com.example.miaosh.util.StringUtil;

@RestController
@RequestMapping("/item")
public class ItemController {

	@Autowired
	private ItemModelService itemModelService;

	@Autowired
	private OrderCoreService orderCoreService;

	@Autowired
	private SequenceInfoService SequenceInfoService;

	@Autowired
	private UserInfoService userInfoService;

	@Autowired
	private ItemStockService itemStockService;

	@Autowired
	private PromoModelService promoModelServicel;

	@RequestMapping("/core")
	public ResultUnify insertItemCore(String title, Float price, String description, Integer stock, String imgUrl) {
		ResultUnify result = new ResultUnify();
		if (StringUtil.isEmpty(title, price, description, stock, imgUrl)) {
			return result.custom(null, 415, "缺少必传参数...");
		}
		if (price < 0) {
			return result.custom(null, 400, "商品价格不能为负数...");
		}
		ItemModel itemModelInfo = new ItemModel();
		itemModelInfo.setTitle(title);
		itemModelInfo.setPrice(price);
		itemModelInfo.setDescription(description);
		itemModelInfo.setImgUrl(imgUrl);
		int resultCount = itemModelService.save(itemModelInfo);
		if (resultCount < 1) {
			return result.custom(null, 400, "添加商品失败...");
		}
		ItemStock itemStock = new ItemStock();
		itemStock.setStock(stock);
		itemStock.setItemId(itemModelInfo.getId());
		itemStockService.save(itemStock);
		return result.custom(null, 200, "添加商品成功...");
	}

	/**
	 * 查询所以商品
	 * 
	 * @return
	 */
	@RequestMapping("/list")
	public ResultUnify listItemCore() {
		ResultUnify result = new ResultUnify();
		return result.success(itemModelService.listInfo());
	}

	/**
	 * 查询单个商品
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/find")
	public ResultUnify qurryItemCore(Integer id) {
		ResultUnify result = new ResultUnify();
		if (StringUtil.isEmpty(id)) {
			return result.custom(null, 415, "缺少必传参数...");
		}
		ItemModel itemModelInfo = new ItemModel();
		itemModelInfo.setId(id);
		itemModelInfo = itemModelService.findById(id);
		if (itemModelInfo == null) {
			return result.custom(null, 400, "没有此商品...");
		}
		return result.success(itemModelInfo);
	}

	/**
	 * 订单的添加
	 * 
	 * @param orderCore
	 * @return
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws Exception
	 */
	@RequestMapping("/insertOrderCore")
	public ResultUnify insertOrderCore(Integer itemId, Integer userId, Integer amount, String token)
			throws InstantiationException, IllegalAccessException {
		ResultUnify result = new ResultUnify();
		if (StringUtil.isEmpty(itemId, userId, amount)) {
			return result.custom(null, 400, "缺少必传参数...");

		}
		// 校验下单状态，下单商品是否存在，用户是否合法，购买数量是否真确
		ItemModel itemModelInfo = itemModelService.findById(itemId);
		if (itemModelInfo == null) {
			return result.custom(null, 400, "没有此商品...");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", userId);
		UserInfo userInfo = userInfoService.getRecord(map);
		if (userInfo == null) {
			return result.custom(null, 400, "该用户不存在...");
		}
		if (amount <= 0 || amount > 99) {
			return result.custom(null, 400, "购买数量不正确...");
		}
		// 落单减库存，（{支付减库存}
		if (false == itemStockService.decreaseStock(itemId, amount)) {
			return result.custom(null, 400, "库存数量不足...");
		}
		// 对应的销量增加
		int resuntCount = itemModelService.update(itemId);
		if (resuntCount < 1) {
			return result.custom(null, 400, "更新销量失败...");
		}
		// 订单号有16位(16位订单拼接生成)
		StringBuilder stringBuilder = new StringBuilder();
		// 前8位位时间信息，年月日
		LocalDateTime now = LocalDateTime.now();
		String nowDate = now.format(DateTimeFormatter.ISO_DATE).replace("-", "");
		// 把获取的8位时间放在定义的stringBuilder里
		stringBuilder.append(nowDate);

		// 中间6位为自增序列
		SequenceInfoService.updateOne("order_info");
		SequenceInfo sequenceInfo = SequenceInfoService.qurrey("order_info");
		if (sequenceInfo.getCurrentValue().length() < 7) {
			for (int i = 0; i < 6 - sequenceInfo.getCurrentValue().length(); i++) {
				stringBuilder.append(0);
			}
		}
		if (sequenceInfo.getCurrentValue().length() > 6) {
			int cc = SequenceInfoService.Zoo("order_info");
			return result.custom(null, 400, "重置自增数为：" + (cc - 1));
		}
		// 数据库查询的值
		stringBuilder.append(sequenceInfo.getCurrentValue());
		// 写死后2位
		stringBuilder.append("01");
		// stringBuilder.append(sequenceInfo.getCurrentValue()).append("00")拼接完成的单号
		System.out.println(stringBuilder);
		PromoModel promoModelInfo = promoModelServicel.findById(itemId);
		if (promoModelInfo != null) {

			long count = orderCoreService.getByMapTotal(map);
			if (count != 0) {
				return result.custom(null, 400, "此活动你已参与，请勿重复参与，谢谢合作");
			}
			if (promoModelInfo.getStartDate().after(new Date())) {

				return result.custom(null, 400, "秒杀活动还未开始");
			}
			if (promoModelInfo.getEndDate().before(new Date())) {

				// 如果秒杀活动已结束，则按原价订单入库
				// 订单入库
				OrderCore orderCore = new OrderCore();
				orderCore.setUserId(userId);
				orderCore.setId(stringBuilder.toString());
				orderCore.setAmount(amount);
				orderCore.setItemId(itemId);
				orderCore.setItemPrice(itemModelInfo.getPrice());
				orderCore.setOrderPrice(itemModelInfo.getPrice() * amount);
				orderCore.setPromoId(0);
				orderCore.setPromoStatus(0);
				orderCoreService.save(orderCore);
				// 返回前端
				orderCore.setCreateTime(new Date());
				return result.success(orderCore);
			}
			// 订单入库
			OrderCore orderCore = new OrderCore();
			orderCore.setUserId(userId);
			orderCore.setId(stringBuilder.toString());
			if (amount > 1) {
				return result.custom(null, 400, "此商品为秒杀价，最多购买一个");
			}
			orderCore.setAmount(amount);
			orderCore.setItemId(itemId);
			orderCore.setItemPrice(itemModelInfo.getPrice());
			orderCore.setOrderPrice(promoModelInfo.getPromoItemPrice());
			orderCore.setPromoId(promoModelInfo.getId());
			orderCore.setPromoStatus(1);
			orderCoreService.save(orderCore);
			orderCore.setCreateTime(new Date());
			return result.success(orderCore);
		}

		// 订单入库
		OrderCore orderCore = new OrderCore();
		orderCore.setUserId(userId);
		orderCore.setId(stringBuilder.toString());
		orderCore.setAmount(amount);
		orderCore.setItemId(itemId);
		orderCore.setItemPrice(itemModelInfo.getPrice());
		orderCore.setOrderPrice(itemModelInfo.getPrice() * amount);
		orderCore.setPromoId(0);
		orderCore.setPromoStatus(0);
		orderCoreService.save(orderCore);
		// 返回前端
		orderCore.setCreateTime(new Date());
		return result.success(orderCore);
	}

	/**
	 * 测试订单号的生成（测试案例）
	 */
	@RequestMapping("/addOrderCoreId")
	public ResultUnify addOrderCoreId() {
		ResultUnify result = new ResultUnify();
		// 订单号有16位(16位订单拼接生成)
		StringBuilder stringBuilder = new StringBuilder();
		// 前8位位时间信息，年月日
		LocalDateTime now = LocalDateTime.now();
		String nowDate = now.format(DateTimeFormatter.ISO_DATE).replace("-", "");
		// 把获取的8位时间放在定义的stringBuilder里
		stringBuilder.append(nowDate);

		// 中间6位为自增序列
		SequenceInfoService.updateOne("order_info");
		SequenceInfo sequenceInfo = SequenceInfoService.qurrey("order_info");
		if (sequenceInfo.getCurrentValue().length() < 7) {
			for (int i = 0; i < 6 - sequenceInfo.getCurrentValue().length(); i++) {
				stringBuilder.append(0);
			}
		}
		if (sequenceInfo.getCurrentValue().length() > 6) {
			int cc = SequenceInfoService.Zoo("order_info");
			return result.custom(null, 400, "重置自增数为：" + (cc - 1));
		}
		// 数据库查询的值
		stringBuilder.append(sequenceInfo.getCurrentValue());
		// 写死后2位
		stringBuilder.append("01");
		// stringBuilder.append(sequenceInfo.getCurrentValue()).append("00")拼接完成的单号
		System.out.println(stringBuilder);
		return result.success(stringBuilder);
	}

	/**
	 * 字增6位数。（测试案例）
	 * 
	 * @return
	 */
	@RequestMapping("/add")
	public ResultUnify update() {
		int a = SequenceInfoService.updateOne("order_info");
		ResultUnify result = new ResultUnify();
		SequenceInfo sequenceInfo = SequenceInfoService.qurrey("order_info");
		StringBuffer str = new StringBuffer();
		if (sequenceInfo.getCurrentValue().length() < 7) {
			for (int i = 0; i < 6 - sequenceInfo.getCurrentValue().length(); i++) {
				str.append(0);
			}
		}
		if (sequenceInfo.getCurrentValue().length() > 6) {
			int cc = SequenceInfoService.Zoo("order_info");
			return result.custom(null, 400, "重置自增数为：" + (cc - 1));
		}
		str.append(sequenceInfo.getCurrentValue());
		System.out.println(str);
		System.out.println(a);
		System.out.println(sequenceInfo);
		System.out.println(sequenceInfo.getCurrentValue().length());
		return null;
	}

	// 时间截取案例
	public static void main(String[] args) {
		// 测试日期的生成
		LocalDateTime now = LocalDateTime.now();
		// 去掉 时 分 秒；
		now.format(DateTimeFormatter.ISO_DATE);
		// q去掉-
		now.format(DateTimeFormatter.ISO_DATE).replace("-", "");
		System.out.println(now);
		System.out.println(now.format(DateTimeFormatter.ISO_DATE));
		System.out.println(now.format(DateTimeFormatter.ISO_DATE).replace("-", ""));

	}
}
